package com.noble.meether.chat.ui.imui.util;

import com.noble.glamour.bean.center.user.detail.UserDetail;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.library.log.PLogger;
import com.noble.library.utils.JsonUtil;
import com.noble.meether.chat.MessageConstant;
import com.noble.meether.chat.msgtype.base.BaseMessage;
import com.noble.meether.chat.ui.imui.listener.ReceiveMsgListener;
import com.noble.meether.fragment.mail.bean.UserMessage;
import com.noble.meether.fragment.mail.listener.UpdateMsgListListener;
import com.noble.meether.fragment.mail.store.DBMessageListCache;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 即使通讯聊天工具类
 */
public class IMChatUtil {
    private volatile static IMChatUtil mInstance;

    public static IMChatUtil getInstance() {
        if (mInstance == null) {
            synchronized (IMChatUtil.class) {
                if (mInstance == null) {
                    mInstance = new IMChatUtil();
                }
            }
        }
        return mInstance;
    }

    // ================= 文字/图片/小视频回调 ===============
    private ReceiveMsgListener receiveMsgListener;

    public ReceiveMsgListener getReceiveMsgListener() {
        return receiveMsgListener;
    }

    public void setReceiveMsgListener(ReceiveMsgListener receiveMsgListener) {
        this.receiveMsgListener = receiveMsgListener;
    }

    // ================= MailFragment: 消息列表更新 ===============
    private static List<UserMessage> msgList = Collections.synchronizedList(new ArrayList<>());  // 信箱数据列表

    public List<UserMessage> getMsgDBList() {
        return msgList;
    }

    public void clearMsgDBList() {
        if (msgList != null) {
            msgList.clear();
        }
    }

    /**
     * 查询数据库表
     */
    public void queryMsgDBList() {
        try {
            ModuleMgr.getDbMgr().getMsgListCache().queryMsgList(new DBMessageListCache.DBMessageListCallback() {
                @Override
                public void onFailure(int code, String message) {
                    ModuleMgr.getOfflineMgr().getOfflineMsg();
                }

                @Override
                public void onSuccess(List<UserMessage> data) {
                    if (data != null && data.size() > 0) {
                        msgList.clear();
                        SortList.reSortList(data);
                        msgList.addAll(SortList.removeDuplicateOrder(data));
                    }
                    ModuleMgr.getOfflineMgr().getOfflineMsg();
                }
            });
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
    }

    /**
     * 更新列表
     */
    public synchronized void updateMsgList(BaseMessage baseMessage) {
        try {
            // 消息列表无数据
            if (msgList.size() <= 0) {
                insertNewMsg(baseMessage);
                return;
            }

            long whisperId = baseMessage.getLuidFrom();
            for (int i = 0; i < msgList.size(); i++) {
                // 列表中已有该用户
                if (whisperId == msgList.get(i).getWhisperID()) {
                    updateOldMsg(baseMessage, i);
                    return;
                }
            }

            // 列表中无该用户
            insertNewMsg(baseMessage);
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }

    }

    /**
     * 插入新的聊天列表
     */
    private UserMessage userMessage;

    private void insertNewMsg(BaseMessage baseMessage) {
        ModuleMgr.getCenterMgr().reqOtherInfo(baseMessage.getLuidFrom(), response -> {
            if (!response.isOk()) return;

            UserDetail userDetail = (UserDetail) response.getBaseData();
            userMessage = new UserMessage();
            userMessage.setWhisperID(baseMessage.getLuidFrom());
            userMessage.setNickName(userDetail.getNickname());
            userMessage.setAvatar(userDetail.getAvatar());
            userMessage.setVipStatus(userDetail.getIsVip());
            userMessage.setContent(msgContent(baseMessage));
            userMessage.setUpdateTime(System.currentTimeMillis());
            msgList.add(0, userMessage);
            if (updateMsgListListener != null) {
                updateMsgListListener.refreshMsgList();
            }

            // 插入数据库
            ModuleMgr.getDbMgr().getMsgListCache().insertMsg(userMessage, null);
        });
    }

    /**
     * 更新已经存在列表
     */
    private void updateOldMsg(BaseMessage baseMessage, int finalI) {
        ModuleMgr.getCenterMgr().reqOtherPartInfo(baseMessage.getLuidFrom(), new String[]{"Avatar", "NickName", "IsVip"}, response -> {
            JSONObject jsonObject = response.getResponseObject();
            UserMessage info = msgList.remove(finalI);
            info.setNickName(jsonObject.optString("NickName"));
            info.setAvatar(jsonObject.optString("Avatar"));
            info.setVipStatus(jsonObject.optInt("IsVip"));
            info.setContent(msgContent(baseMessage));
            info.setUpdateTime(System.currentTimeMillis());
            msgList.add(0, info);
            if (updateMsgListListener != null) {
                updateMsgListListener.refreshMsgList();
            }

            ModuleMgr.getDbMgr().getMsgListCache().updateLetter(info);
        });
    }

    private String msgContent(BaseMessage baseMessage) {
        int msgType = baseMessage.getMsgType();
        if (msgType == MessageConstant.MSG_ID_TEXT) {
            JSONObject jsonObject = JsonUtil.getJsonObject(baseMessage.getContent());
            return jsonObject.optString("Text");
        }
        if (msgType == MessageConstant.MSG_ID_PIC) {
            return "[图片]";
        }

        if (msgType == MessageConstant.MSG_ID_VIDEO) {
            return "[视频]";
        }

        if (msgType == MessageConstant.MSG_ID_GIFT) {
            return "[礼物]";
        }
        return "您收到一条未读消息";
    }

    // ============  信箱消息回调 ========================
    private UpdateMsgListListener updateMsgListListener;

    public UpdateMsgListListener getUpdateMsgListListener() {
        return updateMsgListListener;
    }

    public void setUpdateMsgListListener(UpdateMsgListListener updateMsgListListener) {
        this.updateMsgListListener = updateMsgListListener;
    }
}
